package com.lagou.homework4.no4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 */
public class ServerTest {

    public static void main(String[] args) {
        //创建serverSocket类型的对象并提供端口号
        ServerSocket serverSocket = null;
        Socket socket = null;
        ObjectInputStream br = null;
        ObjectOutputStream out = null;
        try {
            serverSocket = new ServerSocket(8888);
            socket = new Socket();
            //等待客户的连接请求，调用accept()方法
            socket = serverSocket.accept();
            System.out.println("客户端" + serverSocket.getInetAddress() + "连接成功！");
            //使用输入输出流通信
            br = new ObjectInputStream(socket.getInputStream());
            User user = (User) br.readObject();
            System.out.println("接收到的用户名为:"+user.getUsername()+"密码为："+user.getPassword());
            //服 务 器接 收到 对象 后判 断 用户 对象 信息 是否 为 "admin" 和 "123456"，
            // 若 是则 将 UserMessage 对象中的类型改为"success"，否则将类型改为"fail"并回发给客户端
            UserMessage  userMessage = new UserMessage();
            if(user.getUsername().equals("admin")&&user.getPassword().equals("123456")){
                userMessage.setType("success");
                userMessage.setUser(user);
            }else{
                userMessage.setType("fail");
                userMessage.setUser(user);
            }
            out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(userMessage);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=serverSocket){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=socket){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
